package com.duoqin.syncassistant.ui;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.duoqin.chat.ui.ChatListActivity;
import com.duoqin.common.data.QRCodeResponse;
import com.duoqin.common.ui.AbsActivity;
import com.duoqin.common.utils.Utils;
import com.duoqin.guard.data.GuardPostRequest;
import com.duoqin.guard.data.GuardBindData;
import com.duoqin.guard.utils.GuardUtil;
import com.duoqin.syncassistant.R;
import com.duoqin.syncassistant.SyncAssistantApplication;
import com.duoqin.syncassistant.SystemPropertiesProxy;
import com.duoqin.syncassistant.viewmodel.AppViewModel;
import com.duoqin.syncassistant.viewmodel.BaseViewModel;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class RemoteServicesBindingActivity extends AbsActivity {
    private AppViewModel mAppViewModel;
    private ImageView mBindingQRIV, mDuoqinQRIV;
    private View mBindingView, mDuoqinView, mBindingProgressView, mDuoqinProgressView;
    private TextView mQRNoticeTV, mBindingNoticeTV;
    private Button mButton;
    private CheckBox mAcceptTerm;
    private String mQRCodePath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_services_binding);
        setupTitle(getString(R.string.binding));
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mBindingView = findViewById(R.id.binding_qr_code_view);
        mBindingQRIV = findViewById(R.id.binding_qr_code);
        mBindingProgressView = findViewById(R.id.binding_qr_code_progress);
        mDuoqinView = findViewById(R.id.duoqin_qr_code_view);
        mDuoqinQRIV = findViewById(R.id.duoqin_qr_code);
        mQRNoticeTV = findViewById(R.id.duoqin_qr_code_notice);
        mBindingNoticeTV = findViewById(R.id.remote_service_notice);
        mDuoqinProgressView = findViewById(R.id.duoqin_qr_code_progress);
        mButton = findViewById(R.id.action_button);
        mButton.setOnClickListener(this);

        mAcceptTerm = findViewById(R.id.accept_term);
        mAcceptTerm.setOnClickListener(this);
        ((TextView) findViewById(R.id.service_term)).setMovementMethod(LinkMovementMethod.getInstance());

        setupModelObserver();

        // we assume new contacts will be added
        SharedPreferences.Editor editor =
                SyncAssistantApplication.getsInstance().getSharedPreference().edit();
        editor.putBoolean(ChatListActivity.SHARED_PREF_KEY_SHALL_UPDATE_CONTACTS, true);
        editor.apply();

        String otaTag = com.duoqin.common.utils.SystemPropertiesProxy.get(this, "ro.duoqin.ota.tag");
        if (otaTag != null && otaTag.contains("youdao")) {
            mDuoqinQRIV.setImageResource(R.drawable.youdao_wechat_qr_code);
            mQRNoticeTV.setText(R.string.youdao_qr_code_notice);
            mBindingNoticeTV.setText(R.string.youdao_remote_service_notice);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        showDuoqinQRImage();
    }

    @Override
    public void onClick(View v) {
        if (R.id.action_button == v.getId()) {
            if (View.VISIBLE == mDuoqinView.getVisibility()) {
                mDuoqinView.setVisibility(View.GONE);
                mBindingView.setVisibility(View.VISIBLE);
                showBindingProgress(true);
                if (TextUtils.isEmpty(mQRCodePath)) {
                    getBindingQRImage();
                } else {
                    showBindingQRImage();
                }
                mButton.setText(R.string.done);
            } else if (View.VISIBLE == mBindingView.getVisibility()) {
                finish();
            }
        } else if (R.id.accept_term == v.getId()) {
            mButton.setEnabled(mAcceptTerm.isChecked());
        } else {
            super.onClick(v);
        }
    }

    private void setupModelObserver() {
        mAppViewModel = ViewModelProviders.of(this).get(AppViewModel.class);
        final Observer<QRCodeResponse> qrCodeObserver = new Observer<QRCodeResponse>() {
            @Override
            public void onChanged(@Nullable QRCodeResponse response) {
                Log.i(TAG, "onChanged QRCodeResponse = " + response);
                if (response != null) {
                    Log.d(TAG, "onChanged code = " + response.getCode()
                            + "; msg = " + response.getMsg());
                    if (BaseViewModel.SERVER_RESULT_SUCCESS == response.getCode()) {
                        Log.d(TAG, "onChanged qrCodePath = " + response.getQrCode());
                        mQRCodePath = response.getQrCode();
                        showBindingQRImage();
                    }
                }
            }
        };
        mAppViewModel.qrCodeResponse().observe(this, qrCodeObserver);
    }

    private void getBindingQRImage() {
        TelephonyManager telephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        GuardBindData.DataBean dataBean = new GuardBindData.DataBean();
        dataBean.setHardware(SystemPropertiesProxy.get(this,
                "ro.product.model", "Qin 2"));
        dataBean.setSwVersion(SystemPropertiesProxy.get(this,
                "ro.duoqin.build.version", "1.0.0"));
        if ("com.duoqin.remotelocating.Binding".equalsIgnoreCase(getIntent().getAction())) {
            dataBean.setType("location");
        }
        GuardBindData guardBindData = new GuardBindData();
        guardBindData.setData(dataBean);
        guardBindData.setImei(Utils.getDeviceToken(this));

        Gson gson = new GsonBuilder().create();
        String dataString = gson.toJson(guardBindData);
        GuardPostRequest guardPostRequest = new GuardPostRequest();
        try {
            guardPostRequest.setSign(GuardUtil.sign(dataString.getBytes(GuardUtil.CHARSET),
                    GuardUtil.PRIVATE_KEY));
            String randKey = GuardUtil.getRandom();
            String data = GuardUtil.encrypt4Base64(dataString, randKey);
            guardPostRequest.setData(data);
//            String key = GuardUtil.publicEncrypt(randKey, GuardUtil.getPublicKey(GuardUtil.PUBLIC_KEY));
            guardPostRequest.setKey(randKey);
//            Log.d(TAG, "sign = " + guardPostRequest.getSign() + "; key = "
//                    + guardPostRequest.getKey() + "; data = " + guardPostRequest.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }

        gson = new GsonBuilder().create();
        String payload = gson.toJson(guardPostRequest);
        mAppViewModel.getQRCode(payload);
    }

    private void showBindingQRImage() {
        Bitmap imageBitmap = null;
        synchronized (AppViewModel.qrCodeLockObj) {
            try {
                imageBitmap = BitmapFactory.decodeFile(mQRCodePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (imageBitmap != null) {
            mBindingQRIV.setImageBitmap(imageBitmap);
            showBindingProgress(false);
        } else {
            Toast.makeText(getApplication(), R.string.network_error_default,
                    Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void showBindingProgress(final boolean show) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
        mBindingProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mBindingProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mBindingProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                mBindingQRIV.setVisibility(!show ? View.VISIBLE : View.GONE);
            }
        });
    }

    private void showDuoqinQRImage() {
        mButton.setText(R.string.next_step);
        mDuoqinView.setVisibility(View.VISIBLE);
        mBindingView.setVisibility(View.GONE);
    }

    private void showDuoqinProgress(final boolean show) {
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
        mDuoqinProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mDuoqinProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mDuoqinProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                mDuoqinQRIV.setVisibility(!show ? View.VISIBLE : View.GONE);
            }
        });
    }
}
